package cn.kvchoi.reactor_simulation;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Selector {
    private final BlockingQueue<Event> queue = new LinkedBlockingQueue<>();

    private final Object lock = new Object();

    //non block cost cpu
    public List<Event> selectNow() {
        return select(0);
    }

    List<Event> select(long timeout) {
        if (timeout > 0) {
            //block to save cpu
            if (queue.isEmpty()) {
                synchronized (lock) {
                    if (queue.isEmpty()) {
                        try {
                            lock.wait(timeout);
                        } catch (InterruptedException ignored) {
                        }
                    }
                }
            }
        }

        List<Event> list = new ArrayList<>();
        queue.drainTo(list);
        return list;
    }

    public void addEvent(Event event) {
        boolean success = queue.offer(event);
        if (success) {
            synchronized (lock) {
                lock.notify();
            }
        }
    }
}